package net.xdclass.config;

import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;

public class MyWebSocketHandler extends TextWebSocketHandler {
    private final Map<String, AtomicLong> sessions = new ConcurrentHashMap<>(); // 存储会话和观看时长

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        sessions.putIfAbsent(session.getId(), new AtomicLong(0)); // 初始化观看时长为0，如果不存在的话
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        // 处理消息，例如更新观看时长等，这里可以忽略因为主要是统计时长不需要处理消息内容
        long duration = Integer.valueOf(message.getPayload()); // 计算观看时长（毫秒）
        sessions.get(session.getId()).addAndGet(duration); // 更新总观看时长（原子操作）
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        long seconds = sessions.get(session.getId()).get(); // 获取总观看时长
        //更新总观看时长到数据库中
        System.out.println("用户总观看时长：" + seconds);
        sessions.remove(session.getId()); // 移除会话信息，防止内存泄漏
    }
}